package sopt.engSearch;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.net.MalformedURLException;
import java.net.URL;
import java.net.URLConnection;
import java.net.URLEncoder;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import javax.xml.parsers.ParserConfigurationException;
import javax.xml.parsers.SAXParser;
import javax.xml.parsers.SAXParserFactory;

import org.apache.tools.ant.filters.StringInputStream;
import org.xml.sax.SAXException;
import org.xml.sax.helpers.DefaultHandler;

import statics.SoptVars;

import com.sun.syndication.feed.synd.SyndEntry;
import com.sun.syndication.feed.synd.SyndFeed;
import com.sun.syndication.io.FeedException;
import com.sun.syndication.io.SyndFeedInput;
import com.sun.syndication.io.XmlReader;

import comm.parsers.NaverLocalResultSAXParserHandler;
import comm.parsers.NaverRangkingResultSAXParserHandler;
import comm.parsers.NaverSearchResultSAXParserHandler;
import comm.parsers.NaverShortcutResultSAXParserHandler;
import comm.parsers.NaverSuggestResultSAXParserHandler;
import comm.util.SoptHashMap;


public class NaverSearchProc {
	
	//검색 (일단 써먹는건 지식인,블로그?
	//파라미터: queryStr 검색할 한글 단어, target 검색영역 지정
	//기본적으로 검색결과는 5개 까지만(속도) 검색 정렬은 유사도를 기준으로
	public static ArrayList getTheSearchResultFromNaverAPI(String queryStr,String target){
		if(target==null || target.length()==0)
			target = SoptVars.naverSearch_target_total;
		ArrayList lt = new ArrayList();
		
		String rssUrl = "";
		try {
			rssUrl = SoptVars.naverRequestUrl
			+"?key="+SoptVars.naverKey
			+"&query="+URLEncoder.encode(queryStr,"UTF-8")
			+"&display=5&start=1"
			+"&target="+target;
		} catch (UnsupportedEncodingException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}

        URL feedUrl = null;
		try {
			feedUrl = new URL(rssUrl);
		} catch (MalformedURLException e1) {
			// TODO Auto-generated catch block
			e1.printStackTrace();
		}
		
        try {
            SyndFeedInput input = new SyndFeedInput();
            SyndFeed feed = input.build(new XmlReader(feedUrl));
 
            List entries = feed.getEntries();
            for (int i = 0; i < entries.size(); i++) {
                SyndEntry entry = (SyndEntry) entries.get(i);
                SoptHashMap hm = new SoptHashMap();
                hm.put("author", entry.getAuthor());
                hm.put("buildTime", entry.getUpdatedDate());
                hm.put("link", entry.getLink());
                hm.put("title", entry.getTitle());
                hm.put("description", entry.getDescription().getValue());
                lt.add(hm);
                
            }
        } catch (IllegalArgumentException e) {
            // ...
        } catch (FeedException e) {
            // ...
        } catch (IOException e) {
            // ...
        }
        System.out.println("네이버 검색 결과");
		System.out.print(lt.toString());
		return lt;
	}
	
	//바로가기 검색
	//query가 영어일때 잘나오넴-ㅁ-ㅋ
	public static SoptHashMap getShortcutUrl(String query){
		if(query==null || query.length()==0)
			query="test";
		
		String reqStr = SoptVars.naverRequestUrl+"?key="+SoptVars.naverKey+"&query="+query+"&target=shortcut";
		
		String label = "";
		String link = "";
		NaverShortcutResultSAXParserHandler soptDh = new NaverShortcutResultSAXParserHandler();
		
		try{
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			parser.parse(reqStr, soptDh);
			
			label = soptDh.getLabel();
			link = soptDh.getLink();
		} catch (ParserConfigurationException e) {
			  e.printStackTrace();
		 } catch (SAXException e) {
		  e.printStackTrace();
		 } catch (IOException e) {
		  e.printStackTrace();
		 }
		
        SoptHashMap hm = new SoptHashMap();
		hm.put("link", link);
		hm.put("label", label);
		
		System.out.println("네이버 바로가기 ===========");
		System.out.println(hm.toString());
		
		return hm;
        
	}
	
	
	//현재 이슈 키워드 검색
	public static ArrayList getCurrentIssueKeyword(String query){
		if(query==null||query.length()==0)
			query = SoptVars.naverRank_query_total;
		
		ArrayList lt = new ArrayList();
		String reqStr = SoptVars.naverRequestUrl+"?key="+SoptVars.naverKey+"&query="+query+"&target="+SoptVars.naverSearch_target_ranking;
		
		NaverRangkingResultSAXParserHandler soptDh = new NaverRangkingResultSAXParserHandler();
		
		try{
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			parser.parse(reqStr, soptDh);
			
			
			lt = soptDh.getItemList();
		} catch (ParserConfigurationException e) {
			  e.printStackTrace();
		 } catch (SAXException e) {
		  e.printStackTrace();
		 } catch (IOException e) {
		  e.printStackTrace();
		 }
		
       
        System.out.println("네이버 검색어 랭킹===========");
		System.out.print(lt.toString());
		
		return lt;
	}
	
	
	//네이버 추천 검색어
	//일단 5개 기본 출력
	public static ArrayList getSuggestQueryList(String queryStr,int display) throws UnsupportedEncodingException{
		if(display<1)display=5;
		ArrayList lt = new ArrayList();
		String rssUrl = "http://openapi.naver.com/search?key="+SoptVars.naverKey+"&query="+URLEncoder.encode(queryStr,"UTF-8")+"&target=recmd";
		
		System.out.println(rssUrl);
		NaverSuggestResultSAXParserHandler soptDh = new NaverSuggestResultSAXParserHandler();
		
		try{
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			
			parser.parse(rssUrl, soptDh);
			
			lt = soptDh.getItemList();
			
			for(int i=lt.size()-1;i>=display;i--){
				lt.remove(i);
			}
		} catch (ParserConfigurationException e) {
			  e.printStackTrace();
		 } catch (SAXException e) {
		  e.printStackTrace();
		 } catch (IOException e) {
		  e.printStackTrace();
		 }
		 String result = "";
		 if(lt==null){
			 try{
			URL url = new URL(rssUrl);
            URLConnection connection = url.openConnection();
            

            //내용을 읽어오기위한 InputStream객체를 생성한다..
            InputStream is = connection.getInputStream();
            
            
            InputStreamReader isr = new InputStreamReader(is,"UTF-8");
            BufferedReader br = new BufferedReader(isr);
            
            //내용을 읽어서 화면에 출력한다..
            String buf = null;
            
            while(true){
                buf = br.readLine();
                if(buf!=null)result+=buf;
                else break;
                
                //System.out.println(buf);
            }
			 }catch (IOException e){
				 
			 }
			 
			
		 }
		 
		 System.out.println(result);
		 
		return lt;
	}
	
	//검색 결과를 영어로 번역 하는 메소드 (hm, API종류)
	//최종 결과 String 생성
	public static String getTranslatedResultSearch(SoptHashMap hm,String target) throws UnsupportedEncodingException{
		if(target==null || target.length()==0){
			target=SoptVars.naverSearch_target_kin;
		}
		String result = "";
		ArrayList lt = null;
		
		
	        String resultTrans = hm.get("Q").toString();
	      
        	lt = getTheSearchResultFromNaverAPI(resultTrans,target);
	        
	        if(lt!=null)
	       	for(int i=0;i<lt.size();i++){
	       		SoptHashMap tempHm = new SoptHashMap();
	       		tempHm = (SoptHashMap)lt.get(i);
	       		
	       		result += "<a href='translatedPage.jsp?u="+tempHm.get("LINK").toString()+"' target='_blank'>"
	       			+TranslateProc.getTranslatedString(tempHm.get("TITLE").toString(),SoptVars.KOR_TO_ENG)
	       			+"</a>"
	       			+"<p>"+TranslateProc.getTranslatedString(tempHm.get("DESCRIPTION").toString(),SoptVars.KOR_TO_ENG)+"</p>";
	       	}
	       	return result;
	}
	
	
	//거의 네이버 로컬 전용 -ㅁ-;;
	public static String getTranslatedResultSearch(ArrayList lt, int curpage, String category) throws UnsupportedEncodingException{
		if(category==null || category.length()==0){
			category=SoptVars.Menu_Category_Local;
		}
		String result = "";
		int totalcount = 0;
		int count = 0;
		if(lt!=null && lt.size()>0){
			SoptHashMap countHm = (SoptHashMap)lt.get(0);
			if(countHm.get("TOTALCOUNT")!=null)
				totalcount = Integer.parseInt(countHm.get("TOTALCOUNT").toString());
			if(curpage==1){
				result +="<div id='resultTotalCountHeader'>" +
						"<div id='resultHeaderCategory'>" +
						"<p>" +
						"Current Search Area : <b>" +
						category +
						"</b>" +
						"</p>" +
						"</div>" +
						"<div id='resultHeaderCount'>";
				count = lt.size();
				
				result+=
						"<p><span id='countOfResult'>"+count+"</span> Results" +
						" / Total:" +
						totalcount +
						"</p>" +
						"</div>" +
						"<div class='clear'></div>" +
						"</div>";
				
	       		
			}
			result +="<div id='searchResultTotalContainer'>";
			String transTitle = "";
       		String transDesc = "";
       		String link = ""; 
       		String telephone = "";
       		String address = "";
       		String mapx="";
       		String mapy="";
       		
			if(category.equals(SoptVars.Menu_Category_Local)){ //네이버 지역 검색
				result+="<div id='showMapBg'>" +
						"<div id='showMapHeader'><span id='mapTitle'></span><input type='button' value='close' onclick='closeMapLayer()'/></div>" +
						"<div id='MapLayer'></div>" +
						"</div>";
				
			
				for(int i=0;i<lt.size();i++){
		       		SoptHashMap tempHm = new SoptHashMap();
		       		tempHm = (SoptHashMap)lt.get(i);
		       		
		       		transTitle = TranslateProc.getTranslatedString(tempHm.get("TITLE").toString(),SoptVars.KOR_TO_ENG);
		       		transDesc = TranslateProc.getTranslatedString(tempHm.get("DESCRIPTION").toString(),SoptVars.KOR_TO_ENG);
		       		address = TranslateProc.getTranslatedString(tempHm.get("ADDRESS").toString(),SoptVars.KOR_TO_ENG);
		       		link = tempHm.get("LINK").toString();
		       		telephone = tempHm.get("TELEPHONE").toString();
		       		mapx = tempHm.get("MAPX").toString();
		       		mapy = tempHm.get("MAPY").toString();
		       		
		       		
		       		String host = "";
		       		if(link.length()>0){
			       		host = link.substring(7);
			       		host = host.substring(0,host.indexOf("/"));
		       		}
		       		
		       		result +="<div class='g'>";
		       		if(link.length()>0)
		       			result +="<p><a href='translatedPage.jsp?u="+link+"' target='_blank'>";
		       		else
		       			result +="<p><a>";
		       		
		       		result +=
	       				transTitle +
		       			"</a></p>" +
		       			"<p class='translatedDesc'>"+transDesc+"</p>"+
		       			"<p class='translatedDesc'>Phone : "+telephone+"</p>"+
		       			"<p class='translatedDesc'>Address : "+address+"</p>";
		       		result +=
		       			"<p><a href='translatedPage.jsp?u="+link+"' target='_blank' class='linkGreen'>"+host+"</a></p>";
		       		
		       		if(mapx.length()>0 && mapy.length()>0)
		       			result+= "<p><input type='button' title='"+transTitle.replaceAll("<b>", "").replaceAll("</b>", "")+"' value='viewMap' mapx='"+mapx+"' mapy='"+mapy+"' onclick='javascript:showMap(this);' /></p>";
		       		
		       		result+=
       					"</div>";
		       	}
			}
		}
		return result;
	}
	
	//지역 검색
	//정렬은 별점 기준
	//ArrayList에 맵 형태로 들어감:title,link,description,telephone,address,mapx,mapy
	public static ArrayList getLocalSearchList(String queryStr,int curpage,int display) throws UnsupportedEncodingException{
		
		System.out.println("####들어온 값"+queryStr);
		
		if(display<1)display=5;
		if(curpage<1)curpage=1;
		
		int startNo = 1;
		if(curpage>1)startNo=display*curpage;
		
		ArrayList lt = new ArrayList();
		String rssUrl = "http://openapi.naver.com/search?key="
			+SoptVars.naverKey
			+"&query="+URLEncoder.encode(queryStr,"UTF-8")
			+"&target="+SoptVars.naverSearch_target_local
			+"&sort=random"
			+"&start="+startNo
			+"&display="+display;
		System.out.println(rssUrl);
		NaverLocalResultSAXParserHandler soptDh = new NaverLocalResultSAXParserHandler();
		
		try{
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			
			parser.parse(rssUrl, soptDh);
			
			lt = soptDh.getItemList();
			for(int i=lt.size()-1;i>=display;i--){
				lt.remove(i);
			}
		} catch (ParserConfigurationException e) {
			  e.printStackTrace();
		 } catch (SAXException e) {
		  e.printStackTrace();
		 } catch (IOException e) {
		  e.printStackTrace();
		 }
		 System.out.println("=====지역정보 결과");
		System.out.println(lt.toString());
		
		return lt;
	}
	
	
public static ArrayList getNewsResult(String queryStr,int curpage,int display) throws UnsupportedEncodingException{
		
		//System.out.println("####들어온 값"+queryStr);
		
		if(display<1)display=5;
		if(curpage<1)curpage=1;
		
		int startNo = 1;
		if(curpage>1)startNo=display*curpage;
		
		ArrayList lt = new ArrayList();
		String rssUrl = "http://openapi.naver.com/search?key="
			+SoptVars.naverKey
			+"&query="+URLEncoder.encode(queryStr,"UTF-8")
			+"&target="+SoptVars.naverSearch_target_news
			+"&sort=date"
			+"&start="+startNo
			+"&display="+display;
		//System.out.println(rssUrl);
		NaverSearchResultSAXParserHandler soptDh = new NaverSearchResultSAXParserHandler();
		
		try{
			SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
			
			parser.parse(rssUrl, soptDh);
			
			lt = soptDh.getItemList();
			for(int i=lt.size()-1;i>=display;i--){
				lt.remove(i);
			}
		} catch (ParserConfigurationException e) {
			  e.printStackTrace();
		 } catch (SAXException e) {
		  e.printStackTrace();
		 } catch (IOException e) {
		  e.printStackTrace();
		 }
		 //System.out.println("=====뉴스 결과");
		//System.out.println(lt);
		
		return lt;
	}


public static ArrayList getBlogResult(String queryStr,int curpage,int display) throws UnsupportedEncodingException{
	
	//System.out.println("####들어온 값"+queryStr);
	
	if(display<1)display=5;
	if(curpage<1)curpage=1;
	
	int startNo = 1;
	if(curpage>1)startNo=display*curpage;
	
	ArrayList lt = new ArrayList();
	String rssUrl = "http://openapi.naver.com/search?key="
		+SoptVars.naverKey
		+"&query="+URLEncoder.encode(queryStr,"UTF-8")
		+"&target="+SoptVars.naverSearch_target_blog
		+"&sort=date"
		+"&start="+startNo
		+"&display="+display;
	//System.out.println(rssUrl);
	NaverSearchResultSAXParserHandler soptDh = new NaverSearchResultSAXParserHandler();
	
	try{
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		
		parser.parse(rssUrl, soptDh);
		
		lt = soptDh.getItemList();
		for(int i=lt.size()-1;i>=display;i--){
			lt.remove(i);
		}
	} catch (ParserConfigurationException e) {
		  e.printStackTrace();
	 } catch (SAXException e) {
	  e.printStackTrace();
	 } catch (IOException e) {
	  e.printStackTrace();
	 }
	 //System.out.println("=====블로그 결과");
	//System.out.println(lt);
	
	return lt;
}

public static ArrayList getImageResult(String queryStr,int curpage,int display) throws UnsupportedEncodingException{
	
	//System.out.println("####들어온 값"+queryStr);
	
	if(display<1)display=5;
	if(curpage<1)curpage=1;
	
	int startNo = 1;
	if(curpage>1)startNo=display*curpage;
	
	ArrayList lt = new ArrayList();
	String rssUrl = "http://openapi.naver.com/search?key="
		+SoptVars.naverKey
		+"&query="+URLEncoder.encode(queryStr,"UTF-8")
		+"&target="+SoptVars.naverSearch_target_image
		+"&sort=date"
		+"&start="+startNo
		+"&display="+display;
	//System.out.println(rssUrl);
	NaverSearchResultSAXParserHandler soptDh = new NaverSearchResultSAXParserHandler();
	
	try{
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		
		parser.parse(rssUrl, soptDh);
		
		lt = soptDh.getItemList();
		for(int i=lt.size()-1;i>=display;i--){
			lt.remove(i);
		}
	} catch (ParserConfigurationException e) {
		  e.printStackTrace();
	 } catch (SAXException e) {
	  e.printStackTrace();
	 } catch (IOException e) {
	  e.printStackTrace();
	 }
	 //System.out.println("=====이미지 결과");
	//System.out.println(lt);
	
	return lt;
}

public static ArrayList getVidResult(String queryStr,int curpage,int display) throws UnsupportedEncodingException{
	
	//System.out.println("####들어온 값"+queryStr);
	
	if(display<1)display=5;
	if(curpage<1)curpage=1;
	
	int startNo = 1;
	if(curpage>1)startNo=display*curpage;
	
	ArrayList lt = new ArrayList();
	String rssUrl = "http://openapi.naver.com/search?key="
		+SoptVars.naverKey
		+"&query="+URLEncoder.encode(queryStr,"UTF-8")
		+"&target="+SoptVars.naverSearch_target_video
		+"&sort=date"
		+"&start="+startNo
		+"&display="+display;
	System.out.println(rssUrl);
	NaverSearchResultSAXParserHandler soptDh = new NaverSearchResultSAXParserHandler();
	
	try{
		SAXParser parser = SAXParserFactory.newInstance().newSAXParser();
		
		parser.parse(rssUrl, soptDh);
		
		lt = soptDh.getItemList();
		for(int i=lt.size()-1;i>=display;i--){
			lt.remove(i);
		}
	} catch (ParserConfigurationException e) {
		  e.printStackTrace();
	 } catch (SAXException e) {
	  e.printStackTrace();
	 } catch (IOException e) {
	  e.printStackTrace();
	 }
	 //System.out.println("=====동영상 결과");
	//System.out.println(lt);
	
	return lt;
}
	
}
